import { baiduInstance } from '../api/instance'

// 将你的百度智能云凭证配置在此（前端直连仅用于演示/教学，生产请走服务端）
const BAIDU_FACE_API_KEY = 'dO9BtwXCqPVbOmdWfFkAYxKD'
const BAIDU_FACE_SECRET_KEY = 'jRLOhvkliZ9QERoMbkiuuio0Wv9vta92'

// 默认分组与阈值（可按需调整或从后端获取）
const DEFAULT_GROUP_ID_LIST = 'group1'
const DEFAULT_MATCH_THRESHOLD = 80
const DEFAULT_GROUP_ID = 'group1'

type DetectResult = {
    faceToken: string
}

export const faceService = {
    // 获取访问令牌
    async getAccessToken(): Promise<string> {
        const form = `grant_type=client_credentials&client_id=${encodeURIComponent(BAIDU_FACE_API_KEY)}&client_secret=${encodeURIComponent(BAIDU_FACE_SECRET_KEY)}`
        const { data } = await baiduInstance.post('/oauth/2.0/token', form, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        })
        if (!data?.access_token) throw new Error('获取AccessToken失败')
        return data.access_token as string
    },

    // 人脸检测
    async detectFace(base64: string, token: string): Promise<DetectResult> {
        const url = `/rest/2.0/face/v3/detect?access_token=${encodeURIComponent(token)}`
        const payload = {
            image: base64,
            image_type: 'BASE64',
            face_field: 'quality,face_type',
            liveness_control: 'NORMAL',
            quality_control: 'LOW',
            max_face_num: 3,
        }
        const { data } = await baiduInstance.post(url, payload)
        if (data?.error_code) throw new Error(data?.error_msg || '人脸检测失败')
        const faceList = data?.result?.face_list || []
        if (!Array.isArray(faceList) || faceList.length === 0) throw new Error('未检测到人脸')
        return { faceToken: faceList[0]?.face_token as string }
    },

    // 人脸搜索
    async multiSearch(base64: string, token: string, groupIds = DEFAULT_GROUP_ID_LIST): Promise<{ userId: string; score: number } | null> {
        const url = `/rest/2.0/face/v3/multi-search?access_token=${encodeURIComponent(token)}`
        const payload = {
            image: base64,
            image_type: 'BASE64',
            group_id_list: groupIds,
            match_threshold: DEFAULT_MATCH_THRESHOLD,
            quality_control: 'LOW',
            liveness_control: 'NONE',
            max_user_num: 5,
        }
        const { data } = await baiduInstance.post(url, payload)
        if (data?.error_code) throw new Error(data?.error_msg || '人脸搜索失败')
        const result = data?.result
        if (!result || !Array.isArray(result?.face_list) || result.face_list.length === 0) return null
        // 取第一张脸的第一条匹配
        const userList = result.face_list[0]?.user_list
        if (!Array.isArray(userList) || userList.length === 0) return null
        const best = userList[0]
        return { userId: String(best?.user_id ?? ''), score: Number(best?.score ?? 0) }
    },
    // 人脸入库（注册）
    async addUserToFaceset(base64: string, token: string, userId: string, groupId: string = DEFAULT_GROUP_ID) {
        const url = `/rest/2.0/face/v3/faceset/user/add?access_token=${encodeURIComponent(token)}`
        const payload = {
            image: base64,
            image_type: 'BASE64',
            group_id: groupId,
            user_id: userId,
            quality_control: 'NORMAL',
            liveness_control: 'NORMAL',
        }
        const { data } = await baiduInstance.post(url, payload)
        if (data?.error_code) throw new Error(data?.error_msg || '人脸入库失败')
        return data
    },
}



